"""
多轮对话系统 FastAPI 路由
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any, Optional

from qwen.chat import get_chat_system, ChatSystem

router = APIRouter(prefix="/api/chat", tags=["对话"])

# 获取对话系统实例
chat_system = get_chat_system(enable_rag=True)


# ============ 请求/响应模型 ============

class SendMessageRequest(BaseModel):
    """发送消息请求"""
    message: str
    conversation_id: Optional[str] = None
    use_rag: bool = True


class SendMessageResponse(BaseModel):
    """发送消息响应"""
    success: bool
    conversation_id: str
    user_message: str
    assistant_reply: str
    used_rag: bool
    message_count: int
    error: Optional[str] = None


class CreateConversationRequest(BaseModel):
    """创建对话请求"""
    title: Optional[str] = None


class CreateConversationResponse(BaseModel):
    """创建对话响应"""
    conversation_id: str
    title: str


class ConversationInfo(BaseModel):
    """对话信息"""
    conversation_id: str
    title: str
    created_at: str
    updated_at: str
    message_count: int
    last_message: Optional[str] = None
    is_current: bool


class MessageInfo(BaseModel):
    """消息信息"""
    role: str
    content: str
    timestamp: str
    used_rag: Optional[bool] = None


class ConversationHistoryResponse(BaseModel):
    """对话历史响应"""
    conversation_id: str
    messages: List[MessageInfo]


class UpdateTitleRequest(BaseModel):
    """更新标题请求"""
    title: str


# ============ API 端点 ============

@router.post("/send", response_model=SendMessageResponse)
async def send_message(request: SendMessageRequest):
    """
    发送消息并获取回复
    
    - 如果 conversation_id 为空，会自动创建新对话
    - 如果启用 RAG，会自动检索相关文档上下文
    """
    try:
        result = chat_system.send_message(
            message=request.message,
            conversation_id=request.conversation_id,
            use_rag=request.use_rag
        )
        
        if result["success"]:
            return SendMessageResponse(
                success=True,
                conversation_id=result["conversation_id"],
                user_message=result["user_message"],
                assistant_reply=result["assistant_reply"],
                used_rag=result["used_rag"],
                message_count=result["message_count"]
            )
        else:
            return SendMessageResponse(
                success=False,
                conversation_id=result.get("conversation_id", ""),
                user_message=request.message,
                assistant_reply="",
                used_rag=False,
                message_count=0,
                error=result.get("error", "未知错误")
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发送消息失败: {str(e)}")


@router.post("/conversations", response_model=CreateConversationResponse)
async def create_conversation(request: CreateConversationRequest):
    """
    创建新对话
    """
    try:
        conversation_id = chat_system.create_conversation(title=request.title)
        metadata = chat_system.conversation_metadata.get(conversation_id, {})
        return CreateConversationResponse(
            conversation_id=conversation_id,
            title=metadata.get("title", "新对话")
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建对话失败: {str(e)}")


@router.get("/conversations", response_model=List[ConversationInfo])
async def get_conversations():
    """
    获取所有对话列表
    """
    try:
        conv_list = chat_system.get_conversation_list()
        return [
            ConversationInfo(
                conversation_id=conv["conversation_id"],
                title=conv["title"],
                created_at=conv["created_at"],
                updated_at=conv["updated_at"],
                message_count=conv["message_count"],
                last_message=conv.get("last_message"),
                is_current=conv.get("is_current", False)
            )
            for conv in conv_list
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话列表失败: {str(e)}")


@router.get("/conversations/{conversation_id}/history", response_model=ConversationHistoryResponse)
async def get_conversation_history(conversation_id: str):
    """
    获取指定对话的历史消息
    """
    try:
        history = chat_system.get_conversation_history(conversation_id)
        return ConversationHistoryResponse(
            conversation_id=conversation_id,
            messages=[
                MessageInfo(
                    role=msg.get("role"),
                    content=msg.get("content"),
                    timestamp=msg.get("timestamp", ""),
                    used_rag=msg.get("used_rag")
                )
                for msg in history
            ]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话历史失败: {str(e)}")


@router.put("/conversations/{conversation_id}/switch")
async def switch_conversation(conversation_id: str):
    """
    切换到指定对话
    """
    try:
        success = chat_system.switch_conversation(conversation_id)
        if success:
            return {"success": True, "message": f"已切换到对话: {conversation_id}"}
        else:
            raise HTTPException(status_code=404, detail="对话不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"切换对话失败: {str(e)}")


@router.put("/conversations/{conversation_id}/title", response_model=dict)
async def update_conversation_title(conversation_id: str, request: UpdateTitleRequest):
    """
    更新对话标题
    """
    try:
        success = chat_system.update_conversation_title(conversation_id, request.title)
        if success:
            return {"success": True, "message": "标题更新成功"}
        else:
            raise HTTPException(status_code=404, detail="对话不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新标题失败: {str(e)}")


@router.delete("/conversations/{conversation_id}")
async def delete_conversation(conversation_id: str):
    """
    删除指定对话
    """
    try:
        success = chat_system.delete_conversation(conversation_id)
        if success:
            return {"success": True, "message": "对话已删除"}
        else:
            raise HTTPException(status_code=404, detail="对话不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除对话失败: {str(e)}")


@router.get("/current")
async def get_current_conversation():
    """
    获取当前对话ID
    """
    try:
        current_id = chat_system.current_conversation_id
        if current_id:
            return {
                "conversation_id": current_id,
                "metadata": chat_system.conversation_metadata.get(current_id, {})
            }
        else:
            return {"conversation_id": None, "message": "当前没有活动对话"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取当前对话失败: {str(e)}")

